package com.future.mayi.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.adapter.AssociateAdapter;
import com.future.mayi.adapter.SearchGoodsAdapter;
import com.future.mayi.app.App;
import com.future.mayi.model.SearchGoodsItemModel;
import com.future.mayi.model.interfaces.OnItemClickListener;
import com.future.mayi.response.SearchGoodsResponse;
import com.future.mayi.response.SearchTipResponse;
import com.future.mayi.response.TypeListResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.RecyclerItemDecoration;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.future.mayi.view.xrecyclerview.XRecyclerView;
import com.future.mayi.widget.FlowLayout;
import com.future.mayi.widget.SearchSelectView;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity implements View.OnClickListener, OnItemClickListener, XRecyclerView.LoadingListener, SearchSelectView.TypeViewListener {


    @BindView(R.id.tv_search)
    EditText tvSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.ll_cache)
    LinearLayout llCache;
    @BindView(R.id.flow_layout)
    FlowLayout mFlowLayout;
    @BindView(R.id.search_hot)
    FlowLayout searchHot;
    @BindView(R.id.ll_null)
    LinearLayout llNull;
    //    @BindView(R.id.tv_zh)
//    TextView tvZh;
//    @BindView(R.id.tv_price)
//    TextView tvPrice;
//    @BindView(R.id.tv_new)
//    TextView tvNew;
//    @BindView(R.id.tv_select)
//    TextView tvSelect;
    @BindView(R.id.ll_content)
    View llContent;
    @BindView(R.id.recycler_view)
    XRecyclerView recyclerView;
    @BindView(R.id.ssv)
    SearchSelectView ssv;

    RecyclerView rvAssociate;
    AssociateAdapter associateAdapter;
    PopupWindow popupWindow;

    private List<String> cacheList;
    public List<String> searchHotList;

    private LayoutInflater mInflater;
    private SearchGoodsAdapter adapter;

    boolean isHit = true;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_search);
    }

    @Override
    protected void initView() {
        mInflater = LayoutInflater.from(this);
        adapter = new SearchGoodsAdapter(this, recyclerView);
        recyclerView.setHasFixedSize(true);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.addItemDecoration(new RecyclerItemDecoration(5, 2));
        linearLayoutManager.setStackFromEnd(false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        View contentView = View.inflate(this, R.layout.item_associate_list, null);
        rvAssociate = contentView.findViewById(R.id.item_associate_rv);
        rvAssociate.setLayoutManager(new LinearLayoutManager(this));
        associateAdapter = new AssociateAdapter(this, null);
        associateAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItem(View view, int position) {
                isHit = false;
                String content = associateAdapter.getItem(position);
                tvSearch.setText(content);
                tvSearch.setSelection(content.length());
                search(content);
            }

            @Override
            public void OnLongItem(View view, int position) {

            }
        });
        rvAssociate.setAdapter(associateAdapter);
        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setClippingEnabled(true);
//        initSearchAssociate();
    }


    @SuppressWarnings("unchecked")
    @Override
    protected void initDates() {

        new HttpRequest<TypeListResponse>()
                .with(this)
                .setApiCode(ApiCst.hotKeyword)
                .setListener(new HttpRequest.OnNetworkListener<TypeListResponse>() {
                    @Override
                    public void onSuccess(TypeListResponse response) {
//                        ssv.setData(response.model);
                        if (response.model.getHot_keyword_list() == null || response.model.getHot_keyword_list().size() == 0)
                            return;
                        searchHotList = response.model.getHot_keyword_list();
                        setHotView();
                    }

                    @Override
                    public void onFail(String message, TypeListResponse response) {

                    }
                })
                .start(new TypeListResponse());


        String cache = (String) SharedPreferencesUtils.get(mContext, SharedPreferencesUtils.SpEnum.UserSearchCache, "");
        if (!TextUtils.isEmpty(cache)) {
            cacheList = App.getGson().fromJson(cache, new TypeToken<List<String>>() {
            }.getType());
        }
        setCacheView();
    }

    @Override
    protected void initListener() {
        recyclerView.setLoadingListener(this);
        adapter.setOnItemClickListener(this);
        tvSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == keyEvent.KEYCODE_ENTER) {
                    search(tvSearch.getText().toString());
                }
                return false;
            }
        });
        tvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(tvSearch.getText())) {
                    if (ivClear.getVisibility() == View.VISIBLE) {
                        ivClear.setVisibility(View.GONE);
//                        setLlContentVis(false);
                    }
                } else {
                    if (ivClear.getVisibility() == View.GONE)
                        ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().trim().isEmpty() && isHit) {
                    searchAssociate(s.toString());
                } else {
                    associateAdapter.clear();
                    popupWindow.dismiss();
                }
            }
        });
        ssv.setListener(this);
    }

    private String searchContent;

    private void search(String text) {
        if (TextUtils.isEmpty(text)) {
            toast("请输入搜索内容");
            return;
        }

        CommonUtils.hideKeyboard(tvSearch, this);
        setLlContentVis(true);
        page = 0;
        searchContent = text;
        minPrice = 0;
        maxPrice = 0;

        search();
        if (cacheList != null && cacheList.size() > 0) {
            int delete = -1;
            for (int i = 0; i < cacheList.size(); i++) {
                if (cacheList.get(i).equals(text)) {
                    delete = i;
                }
            }
            if (delete != -1)
                cacheList.remove(delete);
            cacheList.add(0, text);
        } else {
            cacheList = new ArrayList<>(1);
            cacheList.add(text);
        }
        setCacheView();
        SharedPreferencesUtils.set(mContext, SharedPreferencesUtils.SpEnum.UserSearchCache, App.getGson().toJson(cacheList));
    }


    @OnClick({R.id.iv_title_left, R.id.tv_clear, R.id.iv_clear,
//            R.id.ll_zh, R.id.ll_price, R.id.ll_new,R.id.ll_select
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left: {
                onBackPressed();
            }
            break;
            case R.id.tv_clear: {
                llCache.setVisibility(View.GONE);
                mFlowLayout.setVisibility(View.GONE);
                if (cacheList != null && cacheList.size() > 0)
                    cacheList.clear();
                cacheList = new ArrayList<>();
                SharedPreferencesUtils.set(mContext, SharedPreferencesUtils.SpEnum.UserSearchCache, "");
            }
            break;
            case R.id.iv_clear: {
                tvSearch.setText("");
            }
            break;
//            case R.id.ll_zh:
//                select(tvZh);
//                break;
//            case R.id.ll_price:
//                select(tvPrice);
//                break;
//            case R.id.ll_new:
//                select(tvNew);
//                break;
//            case R.id.ll_select:
//                ssv.setVisibility(View.VISIBLE);
//                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getTag() instanceof Integer && v instanceof TextView) {
            isHit = false;
            String content = ((TextView) v).getText().toString();
            tvSearch.setText(content);
            tvSearch.setSelection(content.length());
            search(content);
        }
    }

    private void setLlContentVis(boolean isVis) {
        if (llContent.getVisibility() == (isVis ? View.VISIBLE : View.GONE)) return;
        llNull.setVisibility(isVis ? View.GONE : View.VISIBLE);
        llContent.setVisibility(isVis ? View.VISIBLE : View.GONE);
        page = 0;
        if (!isVis) {

            sort = 0;
            minPrice = 0;
            maxPrice = 0;
            brand_id = null;
            cate_id = null;
            quality_id = null;
            is_sales = 0;
            is_credit = 0;

//            tvZh.setTextColor(getResources().getColor(R.color.main_color));
//            tvNew.setCompoundDrawables(null, null, null, null);
//            tvPrice.setCompoundDrawables(null, null, null, null);
//            tvNew.setTextColor(getResources().getColor(R.color.main_text_color));
//            tvPrice.setTextColor(getResources().getColor(R.color.main_text_color));
            ssv.clear();
        }
        searchContent = "";
        adapter.setList(new ArrayList<SearchGoodsItemModel>());

    }


    @Override
    public void OnItem(View view, int position) {
        Intent intent = new Intent(this, GoodsActivity.class);
        intent.putExtra("goodsId", adapter.getList().get(position).getGoods_id());
        startActivity(intent);
    }

    @Override
    public void OnLongItem(View view, int position) {

    }


    private void setCacheView() {
        if (cacheList == null || cacheList.size() == 0) {
            llCache.setVisibility(View.GONE);
            mFlowLayout.setVisibility(View.GONE);
            return;
        } else {
            llCache.setVisibility(View.VISIBLE);
            mFlowLayout.setVisibility(View.VISIBLE);
        }
        if (mFlowLayout.getChildCount() > 0)
            mFlowLayout.removeAllViews();
        for (int i = 0; i < cacheList.size(); i++) {
            TextView tv = (TextView) mInflater.inflate(R.layout.layout_search_item_text, mFlowLayout, false);
            tv.setText(cacheList.get(i));
            tv.setTag(i);
            tv.setOnClickListener(this);
            mFlowLayout.addView(tv);
        }
    }

    private void setHotView() {
        if (searchHotList == null || searchHotList.size() == 0) {
            searchHot.setVisibility(View.GONE);
            return;
        } else {
            searchHot.setVisibility(View.VISIBLE);
        }
        if (searchHot.getChildCount() > 0)
            searchHot.removeAllViews();
        for (int i = 0; i < searchHotList.size(); i++) {
            TextView tv = (TextView) mInflater.inflate(R.layout.layout_search_item_text, searchHot, false);
            tv.setText(searchHotList.get(i));
            tv.setTag(i);
            tv.setOnClickListener(this);
            searchHot.addView(tv);
        }
    }

    @Override
    public void onRefresh() {
        page = 0;
        search();
    }

    @Override
    public void onLoadMore() {
        page++;
        search();
    }

    private int page;
    // 0-综合 1-价格升序 2-价格降序 10-上新降序 11-上新升序
    private int sort = 0;


    private int minPrice = 0;
    private int maxPrice = 0;
    private String brand_id;
    private String cate_id;
    private String quality_id;
    private int is_sales;
    private int is_credit;


    private TextView textView;

    // sort      默认不传为按时间倒序 1-时间 2-热门 3-价格
    // sort_type 排序方式 0-正序 1-倒序
//    private void select(TextView textView) {
//        Drawable drawable = null;
//        if (this.textView == null || this.textView != textView) {
//            if (textView == tvZh) {
//                sort = 0;
//            } else if (textView == tvPrice) {
//                sort = 1;
//            } else if (textView == tvNew) {
//                sort = 10;
//            }
//        } else {
//            if (textView == tvZh) {
//                return;
//            }
//            if (sort == 1 || sort == 2) {
//                sort = sort == 1 ? 2 : 1;
//            } else if (sort == 10 || sort == 11) {
//                sort = sort == 10 ? 11 : 10;
//            }
//
//        }
//
//        if (textView == tvNew || textView == tvPrice) {
//            if (sort == 1 || sort == 10)
//                drawable = getResources().getDrawable(R.drawable.btn_huaxuanshang);
//            else
//                drawable = getResources().getDrawable(R.drawable.btn_huaxuanxian);
//        }
//
//        tvZh.setTextColor(getResources().getColor(R.color.sub_text_color));
//        tvPrice.setTextColor(getResources().getColor(R.color.sub_text_color));
//        tvNew.setTextColor(getResources().getColor(R.color.sub_text_color));
//        tvPrice.setCompoundDrawables(null, null, null, null);
//        tvNew.setCompoundDrawables(null, null, null, null);
//        textView.setTextColor(getResources().getColor(R.color.main_color));
//        if (drawable != null) {
//            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//            textView.setCompoundDrawables(null, null, drawable, null);
//        }
//
//        this.textView = textView;
//        page = 0;
//        recyclerView.refresh();
//    }

    @SuppressWarnings("unchecked")
    private void search() {

//        is_recom	否	int	是否猜你喜欢 -1否 0-首页猜你喜欢 n-商品内猜你喜欢 (n为整数 传入商品ID,默认不传为-1)
//        sort	否	int	排序 0-综合 1-价格升序 2-价格降序 10-上新降序 11-上新升序
//        min_price	否	float	最低价格
//        max_price	否	float	最高价格
//        p	否	int	分页 0开始 1代表第二页 （默认不传为0）
//        psize	否	int	每页条数（默认不传为10）

//        brand_id	否	int	品牌ID
//        cate_id	否	int	品类ID
//        quality_id	否	int	成色ID
//        is_sales	否	int	是否降价 0-否 1-是
//        is_credit	否	int	是否可分期 0-否 1-是

        new HttpRequest<SearchGoodsResponse>()
                .with(this)
                .setApiCode(ApiCst.getSearch)
                .addParam("keyword", searchContent)
//                .setApiCode(ApiCst.getGoodsList)
//                .addParam("keywords", searchContent)
//                .addParam("sort", sort)
//                .addParam("min_price", minPrice)
//                .addParam("max_price", maxPrice)
//                .addParam("p", page)//分页 默认不传 传1代表第二页
//                .addParam("psize", 30)//分页 默认不传 传1代表第二页
//                .addParam("brand_id", brand_id)
//                .addParam("cate_id", cate_id)
//                .addParam("quality_id", quality_id)
//                .addParam("is_sales", is_sales)
//                .addParam("is_credit", is_credit)
                .setListener(new HttpRequest.OnNetworkListener<SearchGoodsResponse>() {
                    @Override
                    public void onSuccess(SearchGoodsResponse response) {
                        if (page == 0 && (response.model == null || response.model.getGoods_list() == null || response.model.getGoods_list().size() == 0))
                            toast("未找到相关内容");
                        HCUtils.refreshListForPage(recyclerView, adapter, response.model.getGoods_list(), page, 10);
                        associateAdapter.clear();
                        popupWindow.dismiss();
                        isHit = true;
                    }

                    @Override
                    public void onFail(String message, SearchGoodsResponse response) {
                        page = HCUtils.refreshFail(recyclerView, page, getApplicationContext(), message);
                        associateAdapter.clear();
                        popupWindow.dismiss();
                        isHit = true;
                    }
                }).start(new SearchGoodsResponse());
    }

    private void searchAssociate(String s) {
        new HttpRequest<SearchTipResponse>()
                .with(this)
                .setApiCode(ApiCst.tipKeyword)
                .addParam("keyword", s)
                .setListener(new HttpRequest.OnNetworkListener<SearchTipResponse>() {
                    @Override
                    public void onSuccess(SearchTipResponse response) {
                        associateAdapter.setList(response.model.getTip_keyword_list());
                        popupWindow.showAsDropDown(tvSearch);
                    }

                    @Override
                    public void onFail(String message, SearchTipResponse response) {
                        associateAdapter.clear();
                        popupWindow.dismiss();
                    }
                }).start(new SearchTipResponse());
    }


    @Override
    public void onTypeChange(String brand_id, String cate_id, String quality_id, int is_sales, int is_credit, int minPrice, int maxPrice) {
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
        this.brand_id = brand_id;
        this.cate_id = cate_id;
        this.quality_id = quality_id;
        this.is_sales = is_sales;
        this.is_credit = is_credit;
        recyclerView.refresh();
    }

    @Override
    protected void onDestroy() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
        super.onDestroy();
    }
}
